
const { ccclass, property, menu } = cc._decorator;

/** ScrollView 子节点 远离中心的节点特殊处理
 * 
 * !! 注意 !!
 * 子节点需要实现 
 * setFar方法
 */
@ccclass
@menu("自定义组件/ScrollView/边缘节点处理")
export default class ScrollViewFarChildren extends cc.Component {


    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;
    content: cc.Node = null;
    scrollviewNode: cc.Node = null;
    private _parentCenter
    key

    _oldY
    onLoad() {
        this.key = "refreshScrollViewFarChildren" + this.uuid
        this.content = this.scrollview.content;
        this.scrollviewNode = this.scrollview.node;
        this._parentCenter = this.scrollview.node.convertToWorldSpaceAR(cc.v2())

    }
    onEnable() {
        this._onScrollEvent();
        this.refresh();
    }
    onDisable() {
        this._offScrollEvent()
    }
    onDestroy() {

    }

    /** 注册滑动监听 */
    private _onScrollEvent() {
        if (!this.scrollviewNode) return;
        this.scrollviewNode.on("scrolling", this._Scrolling, this)
        this.scrollviewNode.on("scroll-ended", this._ScrollEnd, this)
        this.scrollviewNode.on("scroll-began", this._ScrollStart, this)
    }
    /**取消滑动监听 */
    private _offScrollEvent() {
        if (!this.scrollviewNode) return;
        this.scrollviewNode.off("scrolling", this._Scrolling, this)
        this.scrollviewNode.off("scroll-ended", this._ScrollEnd, this)
        this.scrollviewNode.off("scroll-began", this._ScrollStart, this)
    }
    private _Scrolling(event) {
        if (Math.abs(this._oldY - this.content.y) < 10) {
            return
        }
        this._oldY = this.content.y;
        this.refresh();
    }

    _ScrollStart() {
        this._oldY = this.content.y;
        this.refresh();
    }
    _ScrollEnd() {
        this._oldY = 0;
        this.refresh();
    }
    refresh() {
        this._parentCenter = this.scrollview.node.convertToWorldSpaceAR(cc.v2())
        let nodeCenter = this.content.convertToNodeSpaceAR(this._parentCenter)
        let len = this.content.children.length;
        for (let i = 0; i < len; i++) {
            let item = this.content.children[i];
            if (item && item.isValid) {
                //在一定范围内
                let offset = Math.abs(nodeCenter.y - item.y)
                if (offset > (this.content.parent.height + 100)) {
                    continue;
                }
                let item_sc = item.getComponent(item.name)
                //比率
                let rate = 1 - offset / (this.content.parent.height / 2)
                rate = rate < 0 ? 0 : (rate > 1 ? 1 : rate)

                if (item_sc && item_sc["setFar"]) {
                    item_sc.setFar(rate)
                } else {
                    return;
                }
            }
        }
    }


}
